//
//  NSString+Common.m
//  MusicSample
//
//  Created by JackWong on 13-11-19.
//  Copyright (c) 2013年 JackWong. All rights reserved.
//

#import "NSString+Common.h"
#import <sys/utsname.h>
#import <CommonCrypto/CommonDigest.h>
@implementation NSString (Common)

+ (NSString *)escapedString:(NSString *)oldString
{
    NSString *escapedString_lt = [oldString stringByReplacingOccurrencesOfString:@"<" withString:@"&lt"];
    NSString *escapedString = [escapedString_lt stringByReplacingOccurrencesOfString:@">" withString:@"&gt"];
    return escapedString;
}
+ (NSString*)formattedStringForDuration:(double)duration
{
    NSInteger minutes = floor(duration/60);
    NSInteger seconds = round(duration - minutes * 60);
    return [NSString stringWithFormat:@"%ld:%02ld", (long)minutes, (long)seconds];
}

- (NSString *) MD5Hash {
	
	CC_MD5_CTX md5;
	CC_MD5_Init (&md5);
	CC_MD5_Update (&md5, [self UTF8String], [self length]);
	
	unsigned char digest[CC_MD5_DIGEST_LENGTH];
	CC_MD5_Final (digest, &md5);
	NSString *s = [NSString stringWithFormat: @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
                   digest[0],  digest[1],
                   digest[2],  digest[3],
                   digest[4],  digest[5],
                   digest[6],  digest[7],
                   digest[8],  digest[9],
                   digest[10], digest[11],
                   digest[12], digest[13],
                   digest[14], digest[15]];
	
	return s;
	
}

- (BOOL)checkPhoneNumInput {
    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";
    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    NSString * CT = @"^1((33|53|8[09])[0-9]|349)\\d{7}$";
    // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    BOOL res1 = [regextestmobile evaluateWithObject:self];
    BOOL res2 = [regextestcm evaluateWithObject:self];
    BOOL res3 = [regextestcu evaluateWithObject:self];
    BOOL res4 = [regextestct evaluateWithObject:self];
    
    if (res1 || res2 || res3 || res4 )
    {
        return YES;
    }
    else
    {
        return NO;
    }
    
}


+ (CGFloat)calculateTextHeight:(UIFont *)font givenText:(NSString *)text givenWidth:(NSUInteger)width
{
    CGSize size = [text sizeWithFont:font
                   constrainedToSize:CGSizeMake(width, 9999)
                       lineBreakMode:NSLineBreakByWordWrapping];
    CGFloat delta = size.height;
    
    return delta;
}

+ (NSString *)deviceString{
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString * strModel = [NSString stringWithCString:systemInfo.machine
                                             encoding:NSUTF8StringEncoding];
    return [strModel substringWithRange:NSMakeRange(6, 1)];
}

+ (BOOL)IsChinese:(NSString *)str {
    
    for (int i = 0; i < [str length]; i ++)
    {
        NSRange range = NSMakeRange(i, 1);
        NSString *subString = [str substringWithRange:range];
        const char    *cString = [subString UTF8String];
        if (strlen(cString) == 3)
        {
            return YES;
        }
        
    }
    return NO;
}

+ (BOOL)IsSpecial:(NSString *)str{
    NSString *regex = @"[a-zA-Z\u4e00-\u9fa5]+";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isMatch = [pred evaluateWithObject:str];
    return !isMatch;
}

+ (BOOL)ISNumber:(NSString *)Str
{
    NSString *regex =  @"[0-9]+";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isMatch = [pred evaluateWithObject:Str];
    return isMatch;
}
//判断是否包含特殊字符
+ (BOOL)judgeSpecificSymbol:(NSString *)string{
    
    NSError *error = NULL;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^([\u4E00-\u9FA5]|\\s|\\w)*$" options:NSRegularExpressionCaseInsensitive error:&error];
    NSTextCheckingResult *result = [regex firstMatchInString:string options:0 range:NSMakeRange(0, [string length])];
    if (result) {
        if ([[string substringWithRange:result.range] isEqualToString:string]) {
            return YES;
        }else
            return NO;
    }else
        return NO;
}
//判断字符是否超过十二个字符
+ (BOOL)isValidateName:(NSString *)name{
    NSUInteger  character = 0;
    for(int i=0; i< [name length];i++){
        int a = [name characterAtIndex:i];
        if( a > 0x4e00 && a < 0x9fff){ //判断是否为中文
            character +=2;
        }else{
            character +=1;
        }
    }
    if ( character <24) {
        return YES;
    }else{
        return NO;
    }
    
}

//判断是否包含emoji表情
+ (BOOL)stringContainsEmoji:(NSString *)string
{
    __block BOOL returnValue = NO;
    
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length])
                               options:NSStringEnumerationByComposedCharacterSequences
                            usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
                                
                                const unichar high = [substring characterAtIndex: 0];
                                
                                // Surrogate pair (U+1D000-1F9FF)
                                if (0xD800 <= high && high <= 0xDBFF) {
                                    const unichar low = [substring characterAtIndex: 1];
                                    const int codepoint = ((high - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000;
                                    
                                    if (0x1D000 <= codepoint && codepoint <= 0x1F9FF){
                                        returnValue = YES;
                                    }
                                    
                                    // Not surrogate pair (U+2100-27BF)
                                } else {
                                    if (0x2100 <= high && high <= 0x27BF){
                                        returnValue = YES;
                                    }
                                }
                            }];
    
    return returnValue;
}

+ (BOOL)timeSince1970TimeoutWtithString:(NSString *)timeString{
    NSDate  *nowDate = [NSDate date];
    NSTimeInterval  nowTime = [nowDate timeIntervalSince1970];
    NSString  *nowString = [NSString stringWithFormat:@"%li",lrint(nowTime)];
    
    return [nowString compare:timeString] == NSOrderedAscending;
}

- (NSString *)judgeDateString{
    NSArray *dateArr = [self componentsSeparatedByString:@" "];
    NSMutableString *month = [NSMutableString stringWithString:dateArr[0]];
    NSMutableString *time  = [NSMutableString stringWithString:dateArr[1]];
    
    NSDate *now = [NSDate date];
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYY/MM/dd"];
    
    NSString *currentDateStr = [dateformatter stringFromDate:now];
    if ([month isEqualToString:currentDateStr]) {
        return [time substringToIndex:5];
    }
    NSInteger nowYear = [[currentDateStr substringToIndex:3] integerValue];
    NSInteger songYear = [[self substringToIndex:3] integerValue];
    if (nowYear > songYear) {
        return month;
    }else
        return [month substringFromIndex:5];
}

- (NSString *)absoluteUrlWithString{
    NSArray  *stringArray = [self componentsSeparatedByString:@"?"];
    if (stringArray && stringArray.count > 0) {
        return [stringArray firstObject];
    }
    return @"";
}

@end
